﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Solution25
{
    public ListNode ReverseKGroup(ListNode head, int k)
    {
        ListNode end = head;
       
      for (int i = 0; i < k; i++)
        {
            if (end != null)
            {
                end = end.next;
            }
            else
            {
                return head;//k大于链表长度的，不反转，直接返回
            }


        }
        Console.WriteLine(end.val);
        ListNode newHead = Reverse(head, end);
        head.next= ReverseKGroup(head.next, k);//这个head是反转的head（被改变了），是下一组的第一个,搭配这个记录一下head,next的指向 dummyhead.next = end;



        //head.next= ReverseKGroup(end, k);//这个end是没有反转的end（ ListNode end = head;）单独记录了，是下一组的第一个

        return newHead;

    }

    public ListNode Reverse(ListNode head, ListNode end)
    {

        
        ListNode dummyhead = new ListNode();
        dummyhead.next = end;


        while (head != end)
        {
            ListNode next = head.next;
            head.next = dummyhead.next;

            dummyhead.next = head;
            head = next;
        }
        return dummyhead.next;



    }



}

class Program25
{
    static void Main25(string[] args)
    {
        ListNode head = new ListNode(-1);

        for(int i=0; i<10; i++)
        {

            ListNode next = new ListNode(i);
            next.next = head.next; ;
            head.next = next;

        }

        ListNode cur = head.next;


        while (cur != null)
        {

            Console.Write(cur.val+",");
            cur = cur.next;

        }
        Console.WriteLine();
        Solution25 solution = new Solution25();
        ListNode res= solution.ReverseKGroup(head.next, 1);
        while (res != null)
        {

            Console.Write(res.val + ",");
            res=res.next;

        }
        Console.WriteLine();


    }
}
